package cn.youfule.mecs.netty.util;

import java.time.*;
import java.util.Date;
import java.util.Optional;

/**
 * java.util.Date 与 LocalDateTime/LocalDate/LocalTime之间相互转换
 */
public class DateTimeUtils {


    // 01. java.util.Date --> java.time.LocalDateTime
    public static LocalDateTime UDateToLocalDateTime(Date date) {
        return Optional.ofNullable(date).map(d -> {
            Instant instant = d.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            return LocalDateTime.ofInstant(instant, zone);
        }).orElse(null);
    }

    // 02. java.util.Date --> java.time.LocalDate
    public static LocalDate UDateToLocalDate(Date date) {
        return Optional.ofNullable(date).map(d -> {
            Instant instant = d.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
            return localDateTime.toLocalDate();
        }).orElse(null);
    }

    // 03. java.util.Date --> java.time.LocalTime
    public static LocalTime UDateToLocalTime(Date date) {
        return Optional.ofNullable(date).map(d -> {
            Instant instant = d.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
            return localDateTime.toLocalTime();
        }).orElse(null);
    }


    // 04. java.time.LocalDateTime --> java.util.Date
    public static Date LocalDateTimeToUdate(LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).map(d -> {
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = d.atZone(zone).toInstant();
            return Date.from(instant);
        }).orElse(null);
    }


    // 05. java.time.LocalDate --> java.util.Date
    public static Date LocalDateToUdate(LocalDate localDate) {
        return Optional.ofNullable(localDate).map(d -> {
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = d.atStartOfDay().atZone(zone).toInstant();
            return Date.from(instant);
        }).orElse(null);
    }

    // 06. java.time.LocalTime --> java.util.Date
    public static Date LocalTimeToUdate(LocalTime localTime) {
        return Optional.ofNullable(localTime).map(d -> {
            LocalDate localDate = LocalDate.now();
            LocalDateTime localDateTime = LocalDateTime.of(localDate, d);
            ZoneId zone = ZoneId.systemDefault();
            Instant instant = localDateTime.atZone(zone).toInstant();
            return Date.from(instant);
        }).orElse(null);
    }
}
